package org.leon.controller;

import org.leon.pojo.Resume;
import org.leon.service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/resume")
public class ResumeController {

    private ResumeService resumeService;

    @Autowired
    public ResumeController(ResumeService resumeService) {
        this.resumeService = resumeService;
    }

    @RequestMapping("/query")
    public ModelAndView queryAll() {
        List<Resume> resumes = resumeService.queryAll();
        ModelAndView mv = new ModelAndView();
        mv.setViewName("list");
        mv.addObject("result", resumes);
        return mv;
    }

    @RequestMapping("/edit")
    public ModelAndView edit(Resume resume) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/resume/query");
        if (StringUtils.isEmpty(resume.getName())
                && StringUtils.isEmpty(resume.getPhone())
                && StringUtils.isEmpty(resume.getAddress())) {

            return mv;
        }
        resumeService.editResume(resume);
        return mv;
    }

    @RequestMapping("/remove/{id}")
    public ModelAndView delete(@PathVariable("id") Integer id) {
        resumeService.deleteResumeById(id);
        return new ModelAndView("redirect:/resume/query");
    }

    @RequestMapping("/page/edit")
    public ModelAndView goEditPage(Integer id) {
        ModelAndView mv = new ModelAndView("edit");
        if (id != null) {
            Optional<Resume> obj = resumeService.findById(id);
            if (obj.isPresent()) {
                mv.addObject("resume", obj.get());
            }
        }
        return mv;
    }
}
